﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ExtensionMethodExtravaganza
{
	public static class IEnumerableExtensions
	{
		/// <summary>
		/// Performs an action for each item in each collection.
		/// </summary>
		/// <typeparam name="TCommon">A supertype or interface implemented by each member of each collection.</typeparam>
		public static void ForEach<TCommon>(Action<TCommon> action, params IEnumerable[] collections)
		{
			foreach (var col in collections)
			{
				foreach (TCommon item in col)
				{
					action(item);
				}
			}
		}

		/// <summary>
		/// Searches a collection for an item.
		/// </summary>
		/// <returns>The found value, or the default value for "T".</returns>
		public static T Find<T>(this IEnumerable collection, Predicate<T> condition)
		{
			T foundItem = default(T);

			foreach (T item in collection)
			{
				if (condition(item))
				{
					foundItem = item;
					break;
				}
			}

			return foundItem;
		}

		/// <summary>
		/// Returns a strongly-typed IEnumerable wrapper for the <paramref name="collection"/>.
		/// </summary>
		/// <typeparam name="T">The type of element in the collection.</typeparam>
		/// <param name="collection">The collection.</param>
		/// <remarks>Useful for utilizing the extension methods in <see cref="Enumerable"/> against non-generic collections.</remarks>
		public static IEnumerable<T> AsEnumerable<T>(this IEnumerable collection)
		{
			foreach (T item in collection)
			{
				yield return item;
			}
		}
	}
}
